<template>
  <ve-card title="租赁信息" :customContentStyle="{ paddingBottom: 0 }" v-bind="$attrs">
    <template v-if="mode == 'edit' && status == 'orderInProgress'">
      <!-- 还车门店 -->
      <LeaseSite type="returnSite" ref="returnSiteRef" />
    </template>
    <template #forever-show>
      <ve-form-item
        prop="orderSource"
        required
        label="订单来源"
        v-if="(mode != 'edit' || status != 'orderInProgress') && status != 'orderCompleted'"
      >
        <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.orderSourceName }}</text>
        </template>
        <ve-picker-inline
          v-else
          v-model="form.orderSource"
          placeholder="请选择"
          :range="orderSourceEnum"
          unit="arrowRight"
          @change="form.channelType = undefined"
        />
      </ve-form-item>
      <ve-form-item prop="orderAcquisitionType" label="订单获取方式">
        <!-- <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.orderAcquisitionTypeName || '-' }}</text>
        </template>
        <template v-else> -->
        <remote-select
          type="order_acquisition"
          v-model="form.orderAcquisitionType"
          :label="form.orderAcquisitionTypeName"
          @change="changeOrderAcquisitionType"
        />
        <!-- <ve-picker-inline
            v-model="form.orderAcquisitionType"
            placeholder="请选择"
            :range="sysDict.short_order_acquisition_type"
            unit="arrowRight"
            @change="changeOrderAcquisitionType"
          /> -->
        <!-- </template> -->
      </ve-form-item>
    </template>
    <template v-if="mode != 'edit' || (status != 'orderInProgress' && status != 'orderCompleted')">
      <ve-form-item labelPosition="top" prop="timeRange" required label="预计租赁周期" labelTooltipContent="租赁周期最小时间范围为1个月">
        <template #label-extra>
          <view style="color: #3072f6">
            租期：{{ form.leaseNumberStr ? form.leaseNumberStr.replace('月', ' 月 ').replace('天', ' 天') : '- 天' }}
          </view>
        </template>
        <view class="time-range-wrap">
          <view class="quick-date-list">
            <view
              class="quick-date-item"
              :class="{ active: item.active }"
              v-for="(item, index) in quickDateList"
              :key="index"
              @click="quickDateItemClicked(item)"
              >{{ item.label }}</view
            >
          </view>
          <ve-daterange-picker
            v-model:start="form.expectedUseCarTime"
            v-model:end="form.expectedReturnCarTime"
            :config="{
              start: {
                valueFormat: 'YYYY-MM-DD 00:00:00',
              },
              end: {
                valueFormat: 'YYYY-MM-DD 23:59:59',
              },
            }"
            :placeholder="['开始时间', '结束时间']"
            mode="date"
            @confirm="timeRangeConfirmFn"
          />
        </view>
      </ve-form-item>
      <!-- 取车门店 -->
      <LeaseSite :mode="mode" type="site" ref="siteRef" :siteRequired="true" />
      <!-- 还车门店 -->
      <LeaseSite :mode="mode" type="returnSite" ref="returnSiteRef" />
      <!-- 车型选择 -->
      <ve-form-item prop="originalModelId" required label="车型" labelTooltipContent="请先选择租赁周期和取车门店后，再选择车型">
        <CustomSelect tip="请先选择租赁周期和取车门店后，再选择车型" @click="customSelectTap" :modelValue="form.originalModelName" />
      </ve-form-item>
      <ve-form-item label="订单备注" labelPosition="top" :borderBottom="false">
        <ve-input type="textarea" v-model="form.remark" :maxlength="200" />
      </ve-form-item>
    </template>
  </ve-card>
</template>
<script setup>
  import { ref, inject } from 'vue'
  import { computeRentDayAPI, calcDateAPI } from '@/api/order/lOrder'
  import LeaseSite from './lease/lease-site.vue'
  import CustomSelect from '../../components/custom-select.vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { serializeUrlParams } from '@/utils'
  import { useSysDict } from '@/hooks/useDict'
  const sysDict = useSysDict(['short_order_channel_type', 'short_order_acquisition_type'])
  import dayjs from 'dayjs'
  const orderSourceEnum = [{ value: 1, label: '线下订单', disabled: false }]
  var props = defineProps({
    mode: {
      type: String,
      default: '',
    },
    status: {
      type: String,
      default: '',
    },
  })
  const form = inject('form')
  const dict = inject('dict')

  const quickDateList = ref([
    { label: '一个月', active: false },
    { label: '三个月', active: false },
    { label: '半年', active: false },
    { label: '一年', active: false },
    { label: '两年', active: false },
  ])
  // 切换订单获取方式
  // const changeOrderAcquisitionType = (val, item) => {
  //   form.value.orderAcquisitionTypeName = item.label
  // }
  const changeOrderAcquisitionType = (val, option = {}) => {
    form.value.orderAcquisitionType = val
    form.value.orderAcquisitionTypeName = option.name
  }
  const quickDateItemClicked = (clickItem) => {
    const param = {
      startDateTime: dayjs().format('YYYY-MM-DD 00:00:00'),
    }
    switch (clickItem.label) {
      case '一个月':
        param.addMonths = 1
        break
      case '三个月':
        param.addMonths = 3
        break
      case '半年':
        param.addMonths = 6
        break
      case '一年':
        param.addYears = 1
        break
      case '两年':
        param.addYears = 2
        break
    }
    calcDateAPI(param).then((res) => {
      let startStr = param.startDateTime
      let endStr = res.result
      form.value.expectedUseCarTime = startStr
      form.value.expectedReturnCarTime = endStr
      form.value.timeRange = [startStr, endStr]
      timeRangeConfirmFn(form.value.timeRange)
      quickDateList.value.forEach((item) => {
        if (item.label == clickItem.label) {
          item.active = true
        } else {
          item.active = false
        }
      })
    })
  }

  // 日期范围变化，并计算租期
  const timeRangeConfirmFn = (value = []) => {
    // 清空选中
    quickDateList.value.forEach((item) => {
      item.active = false
    })
    form.value.timeRange = value
    // 计算租期
    if (value[0] && value[1]) {
      const param = {
        expectedUseCarTime: value[0],
        expectedReturnCarTime: value[1],
      }
      computeRentDayAPI(param).then((res) => {
        let result = res.result
        let dateStr = result.dateStr
        form.value.leaseMonths = result.months
        form.value.leaseNumberStr = dateStr
      })
      console.log(props.mode)
      // if(props.mode == 'edit'){
      //   // 弹窗提示
      //   uni.showModal({
      //   	title: '提示',
      //   	content: '预计租赁周期变更，租车费产生差异，请到订单详情-费用信息页修改费用信息，请确认是否修改？',
      //     showCancel: false,
      //     confirmText: '我知道了',
      //   });
      // }
    }
  }
  // 选择车型
  const customSelectTap = () => {
    let paramStr = serializeUrlParams({
      siteId: form.value.siteId,
      siteName: form.value.siteName,
      modelId: form.value.originalModelId,
      modelName: form.value.originalModelName,
      startTime: form.value.expectedUseCarTime,
      endTime: form.value.expectedReturnCarTime,
    })
    uni.navigateTo({
      url: `/pages/asset/stock/model-stock/selector?${paramStr}`,
    })
  }
  // 编辑场景下，更新 ShortsiteConfig
  const siteRef = ref()
  const returnSiteRef = ref()
  const updateShortsiteConfig = (siteId, siteName, type) => {
    if (type == 'site') {
      siteRef.value ? siteRef.value.changeSiteIdFn(siteId, { siteName }, true) : ''
    }
    if (type == 'returnSite') {
      returnSiteRef.value ? returnSiteRef.value.changeSiteIdFn(siteId, { siteName }, true) : ''
    }
  }
  defineExpose({
    updateShortsiteConfig,
  })
  onLoad(() => {
    // 车型选择完成
    uni.$on('carModelOk', (option) => {
      form.value.originalModelId = option.id
      form.value.originalModelName = option.modelName

      // 清空车辆信息
      form.value.carId = undefined
      form.value.licenseNo = undefined
      form.value.originalSiteModelName = undefined
    })
    // 上门送取车地址选择完成
    uni.$on('mapSelectSuccess', (info) => {
      console.log(info)
      // 处理选择地图后再次回到当前页，需要取得当前操作的类型（取车地址 or 还车地址）
      let mapSuccessType = uni.getStorageSync('showMapLnglatOperateType')
      if (mapSuccessType == 'site') {
        form.value.address = info.address
        form.value.longitude = info.longitude
        form.value.latitude = info.latitude
      } else {
        form.value.returnAddress = info.address
        form.value.returnLongitude = info.longitude
        form.value.returnLatitude = info.latitude
      }
      uni.removeStorageSync('showMapLnglatOperateType')
    })
  })
  onUnload(() => {
    uni.$off('carModelOk')
    uni.$off('mapSelectSuccess')
  })
</script>
<style lang="less" scoped>
  .custom-select {
    position: relative;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    &_input {
      font-size: 30rpx;
      font-weight: 400;
      line-height: 44rpx;
      text-align: right;
      flex: 1;
    }
    &_arrow {
      flex-shrink: 0;
      margin-left: 10rpx;
      margin-top: 10rpx;
    }
  }
  .disabled-select {
    .custom-select_input {
      color: #cdced0;
    }
  }
  .time-range-wrap {
    flex: 1;
    .quick-date-list {
      display: flex;
      justify-content: space-between;
      margin-bottom: 32rpx;
      .quick-date-item {
        height: 48rpx;
        line-height: 44rpx;
        border-radius: 4rpx 4rpx 4rpx 4rpx;
        opacity: 1;
        border: 2rpx solid #dadbdd;
        padding: 0 24rpx;

        font-size: 24rpx;
        color: #55585f;
        &.active {
          background: #e0edff;
          border: 2rpx solid #3072f6;
          font-weight: 600;
          color: #3072f6;
        }
      }
    }
  }
</style>
